from rest_framework import serializers
from .models import Category,News,Followed,Comment
from users.models import User


class CategorySerializer(serializers.ModelSerializer):
    """用于分类的序列化器"""

    class Meta:
        model = Category
        fields = ("id","name")
        extra_kwargs = {
            "id":{"read_only":True},
            "name":{"read_only":True}
        }


class POSTCategorySerializer(serializers.ModelSerializer):
    """用于创建专栏"""
    class Meta:
        model = Category
        fields = ("id","name","category_url","category_digest")
        extra_kwargs = {
            "id":{"read_only":True},
        }

    def validate(self, attrs):
        """验证数据"""
        print(attrs)
        # 获取专栏名
        name = attrs.get("name")
        category_url = attrs.get("category_url")
        category_digest= attrs.get("category_digest")
        print(name)
        print(category_url)
        print(category_digest)
        # 判断该专栏是否以存在
        try:
            category = Category.objects.get(name=name)
        except Exception as e:
            pass
        else:
            raise serializers.ValidationError("该专栏已存在")

        return attrs


class UserSerializer(serializers.ModelSerializer):
    """定义用户数据的序列化器"""
    class Meta:
        model = User
        fields = ("id","username","img_url")


class NewsSerializer(serializers.ModelSerializer):
    """定义新闻列表的序列化器"""
    user = UserSerializer()
    class Meta:
        model = News
        fields = ("id","title","digest","content","create_time","clicks","clicks","user")


class FollowedSerializer(serializers.ModelSerializer):

    class Meta:
        model = Followed
        fields = ("id","news","user")
        extra_kwargs = {
            "id":{"read_only":True}
        }

    def validate(self, attrs):
        # 获取新闻的id  用户的id
        news_id = attrs["news"]
        user_id = attrs["user"]

        # 查询数据库看看该新闻是否存在
        try:
            news = News.objects.get(id=news_id.id)
        except Exception as e:
            raise serializers.ValidationError("该新闻不存在")

        # 查询该用户是否存在
        try:
            user = User.objects.get(id=user_id.id)
        except Exception as e:
            raise serializers.ValidationError("该用户不存在")

        # 查询该用户是否已经关注该新闻
        try:
            follow = Followed.objects.filter(user_id=user.id,news_id=news.id)
        except Exception as e:
            # raise serializers.ValidationError("该新闻已经被关注")
            pass
        else:
            if follow:
                raise serializers.ValidationError("该新闻已经被关注")

        return attrs

    def create(self, validated_data):
        # 创建对象
        response = super().create(validated_data)
        print(response)
        # 返回对象
        return response


class GETFollowedSerializer(serializers.ModelSerializer):
    """用户查询用户关注的新闻"""
    class Meta:
        model = Followed
        fields = ("id","user","news")
        extra_kwargs = {
            "id":{"read_only":True},
            "user": {"read_only": True},
            "news": {"read_only": True},
        }


class NewsDetailSerializer(serializers.ModelSerializer):
    """新闻详情序话器"""
    user = UserSerializer()
    class Meta:
        model = News
        fields = ("id","title","digest","content","create_time","clicks","clicks","user")


class AuthorNewsSerializer(serializers.ModelSerializer):
    """用于返回新闻详情的作者发布的所有新闻"""
    class Meta:
        model = News
        fields = ("id","title")


class POSTCommentSerializer(serializers.ModelSerializer):
    """用于返回新闻评论的所有数据"""
    # user = UserSerializer()
    class Meta:
        model = Comment
        fields = ("id","news","content","parent","create_time","count","user")
        extra_kwargs = {
            "id":{"read_only":True},
            "count":{"read_only":True},
            "create_time": {"read_only": True},
            # "user":{"read_only": True},
        }

    def validate(self, attrs):
        # 获取数据
        # 获取新闻的对象
        news_id = attrs.get('news')
        # 获取分评论的id
        parent_id = attrs.get('parent',None)
        # 获取user对象
        user_id = attrs.get('user')
        # 判断新闻是否存在
        try:
            news = News.objects.get(id=news_id.id)
        except Exception as e:
            raise serializers.ValidationError("该用户不存在!")

        if parent_id:
            try:
                comment = Comment.objects.get(id=parent_id.id)
            except Exception as e:
                raise serializers.ValidationError("该父评论不存在!")

        # 返回数据
        print(attrs)
        return attrs

    def create(self, validated_data):
        """创建评论"""
        comment = validated_data.get('parent',None)
        # validated_data['user'] = self.context['request'].user

        if comment:
            # 如果父评论存在则父评论的评论数量加一
            comment.count += 1
            comment.save()
            return super().create(validated_data)
        else:
            try:
                del validated_data['parent']
            except Exception as e:
                pass

        return super().create(validated_data)


class GETCommentSerializer(serializers.ModelSerializer):
    """用于返回新闻评论的所有数据"""
    user = UserSerializer()
    class Meta:
        model = Comment
        fields = ("id","news","content","parent","create_time","count","user")
        # extra_kwargs = {
        #     "id":{"read_only":True},
        #     "count":{"read_only":True},
        #     "create_time": {"read_only": True},
        # }


class HeadlineSerializer(serializers.ModelSerializer):
    """提交头条序列化器"""
    class Meta:
        model = News
        fields = ("id","title","user","category","digest","content","create_time")
        extra_kwargs={
            "id":{"read_only":True},
            "create_time":{"read_only":True},
        }

    def validate(self, attrs):
        # 获取用户的值
        # 验证用户是否存在
        # 获取category的值
        category_id = attrs.get('category',None)
        # 判断该值是否存在4
        try:
            category = Category.objects.get(id=category_id.id)
        except Exception as e:
            raise serializers.ValidationError

        return attrs

